﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Data;
using System.Collections;

namespace BDAccessSharingUniqueEventReceiver.EventReceiver1
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
       ExceptionHandler errMsg = new ExceptionHandler();
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
           if (properties.List.ToString() == "Enquiry Access Rights")
           {
               string userName = GetUserName(properties, Convert.ToString(properties.AfterProperties["UserName"]));
               if (!IsUnique(properties.ListItem, userName, properties))
               {
                   properties.Status = SPEventReceiverStatus.CancelWithError;
                   properties.ErrorMessage = "An entry for this user already exists. Please edit the existing entry.";
               }
           }
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
       //    if (properties.List.ToString() == "Enquiry Access Rights")
       //    {
       //        string userName = GetUserName(properties, Convert.ToString(properties.AfterProperties["UserName"]));
       //        if (!IsUnique(properties.ListItem, userName, properties))
       //        {
       //            properties.Status = SPEventReceiverStatus.CancelWithError;
       //            properties.ErrorMessage = "An entry for this user already exists. Please edit the existing entry.";
       //        }
       //    }
       }

       private string GetUserName(SPItemEventProperties properties, string pUserId)
       {
           string userName = "";
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               SPQuery qryUserLogin = new SPQuery();
               qryUserLogin.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + pUserId + " </Value></Eq></Where>";
               SPListItemCollection collUserInfo = Util.GetList(properties.OpenSite().Url, "Home", qryUserLogin, "User Information List");
               userName = collUserInfo.Count > 0 ? Convert.ToString(collUserInfo[0]["Title"]) : "";
           });
           return userName;
       }

       private bool IsUnique(SPListItem pListItem, string pUserName, SPItemEventProperties properties)
       {
           bool isUnique = false;
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               DataTable dt = GetAccessSharingTable(properties);
               //SPUtility.
               //SPUser ouser = properties.OpenWeb().EnsureUser(pUserName);
               var results = (from row in dt.AsEnumerable()
                              where (row.Field<string>("UserName") == pUserName && String.IsNullOrEmpty(Convert.ToString(pListItem["ID"])))
                              || (row.Field<string>("UserName") == pUserName && Convert.ToString(row.Field<Int32>("ID")) != Convert.ToString(pListItem["ID"]))
                              select row);
               //dt.Select("(UserName = " + pUserName + " AND " + String.IsNullOrEmpty(Convert.ToString(pListItem["ID"])) + ") OR " +
               if (results.AsDataView().ToTable().Rows.Count > 0)
                   isUnique = false;
               else
                   isUnique = true;
           });
           return isUnique;
           //foreach (DataRow amount in results)
           //{
           //    decimal amountCountry = Convert.ToDecimal(amount["Amount_x0020_Required"]);
           //    TotalCountryamount.Add(amountCountry);
           //}
       }

       private DataTable GetAccessSharingTable(SPItemEventProperties properties)
       {
           DataTable dt;
           SPQuery query = new SPQuery();
           query.Query = "";
           SPListItemCollection coll = properties.List.GetItems(query);
           dt = coll.GetDataTable();

           return dt;
       } 

       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           base.ItemDeleting(properties);
       }

       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           if (properties.List.ToString() == "Enquiries")
           {
               SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                   try
                   {
                       SPList list;
                       SPListItem listItem;
                       SPWeb web = properties.OpenWeb();
                       list = web.Lists.TryGetList("Enquiry Access Rights");
                       listItem = list.AddItem();
                       listItem["EnquiryId"] = Convert.ToString(properties.ListItem["ID"]);
                       //listItem["Title"] = ddlActionTypes.SelectedValue;
                       string username = properties.ListItem["CreatedByUser"].ToString();
                       SPFieldUserValue userValue = new SPFieldUserValue(web, username);
                       SPUser ouser = userValue.User; // web.EnsureUser(username);
                       SPFieldUserValueCollection value = new SPFieldUserValueCollection();
                       value.Add(new SPFieldUserValue(web, ouser.ID, ouser.Name));
                       listItem["UserName"] = value;
                       listItem["IsEnquiryOwner"] = "1";
                       listItem["ViewAccess"] = "1";
                       listItem["EditAccess"] = "1";

                       web.AllowUnsafeUpdates = true;
                       listItem.Update();
                       web.AllowUnsafeUpdates = false;
                   }
                   catch (Exception ex)
                   {
                       errMsg.SetErrorLog("Error on BDAccessSharingUniqueEventReceiver.EventReceiver1.ItemAdded()", ex.Message, properties);
                   }
               });
           }
       }

       /// <summary>
       /// An item was updated.
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);
       }

       /// <summary>
       /// An item was deleted.
       /// </summary>
       public override void ItemDeleted(SPItemEventProperties properties)
       {
           base.ItemDeleted(properties);

           if (properties.List.ToString() == "Enquiries")
           {
               SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                   try
                   {
                       SPList list;
                       SPListItemCollection coll;
                       SPWeb web = properties.OpenWeb();
                       SPQuery query = new SPQuery();
                       query.Query = "<Where><Eq><FieldRef Name='EnquiryId' /><Value Type='Text'>" + properties.ListItemId.ToString() + "</Value></Eq></Where>";
                       list = web.Lists.TryGetList("Enquiry Access Rights");
                       coll = list.GetItems(query);

                       while (coll.Count > 0)
                       {
                           web.AllowUnsafeUpdates = true;
                           coll[0].Delete();
                           web.AllowUnsafeUpdates = false;
                       }
                   }
                   catch (Exception ex)
                   {
                       errMsg.SetErrorLog("Error on BDAccessSharingUniqueEventReceiver.EventReceiver1.ItemDeleted()", ex.Message, properties);
                   }
               });
           }
       }
    }
}
